#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import json
import random
import time

from gm.api import get_symbol_infos, get_history_symbol, history, get_symbols, stk_get_index_constituents, \
    stk_get_sector_constituents
from gm.enum import ADJUST_PREV

# from akshare import stock_board_concept_name_em, stock_board_concept_hist_em, stock_board_concept_cons_em

from web.api.base_api import BaseApi
from web.api.stock_board_concept_em import stock_board_concept_name_em, stock_board_concept_hist_em, \
    stock_board_concept_cons_em, stock_board_concept_cons_em_2
from web.constants.datetime_format import DatetimeFormat
from web.models.concept_board import ConceptBoard
from web.models.concept_board_index import ConceptBoardIndex
from web.util.datetime_util import DatetimeUtil


class ConceptBoardIndexApi(BaseApi):
    """
    概念板块指数数据api
    """

    def find_current_all_concept_board_name_and_code(self):
        """
        调用akshare接口，查询当前所有概念板块的name和code
        """

        total_concept_board_list = list()
        akshare_concept_board_list = list()
        myquant_concept_board_list = list()
        akshare_concept_board_dataframe = None
        myquant_concept_board_dataframe = None
        try:
            akshare_concept_board_dataframe = stock_board_concept_name_em()
            myquant_concept_board_dataframe = get_symbol_infos(sec_type1=1070, df=True)
        except Exception as e:
            time.sleep(random.uniform(1, 10))
            self.find_current_all_concept_board_name_and_code()
            return

        akshare_concept_board_list = akshare_concept_board_dataframe.values.tolist()
        myquant_concept_board_list = myquant_concept_board_dataframe.values.tolist()

        # 合并两种概念板块
        if akshare_concept_board_list is not None and len(akshare_concept_board_list) > 0 \
            and myquant_concept_board_list is not None and len(myquant_concept_board_list) > 0:
            for myquant_concept_board in myquant_concept_board_list:
                for akshare_concept_board in akshare_concept_board_list:
                    if myquant_concept_board[5] == akshare_concept_board[1]:
                        concept_board = ConceptBoard()
                        concept_board.name = myquant_concept_board[5]
                        concept_board.myquant_code = myquant_concept_board[0]
                        concept_board.akshare_code = akshare_concept_board[2]
                        concept_board.create_time = time.time()
                        total_concept_board_list.append(concept_board)
        else:
            return

        # 这行代码不能注释，否则客户端无法获取数据
        print(json.dumps(total_concept_board_list, default=lambda o: DatetimeUtil.datetime_to_str(o,
                                                                                                  DatetimeFormat.Date_Format_With_Line) if isinstance(
            o, datetime.datetime) else o.__dict__, ensure_ascii=False))

    def find_concept_board_index_by_name_and_begin_date_and_end_date(self, concept_board_name, concept_board_code,
                                                                     begin_date, end_date):
        """
        调用akshare接口，根据name、begin_date和end_date，海量地获取数据
        """

        stock_board_concept_hist_em_df = None
        try:
            # stock_board_concept_hist_em_df = stock_board_concept_hist_em(symbol=concept_board_name, period="daily",
            #                                                              start_date=begin_date, end_date=end_date,
            #                                                              adjust="")
            _begin_date = DatetimeUtil.datetime_str_format(begin_date, DatetimeFormat.Date_Format,
                                                           DatetimeFormat.Date_Format_With_Line)
            _end_date = DatetimeUtil.datetime_str_format(end_date, DatetimeFormat.Date_Format,
                                                         DatetimeFormat.Date_Format_With_Line)
            # stock_board_concept_hist_em_df = get_history_symbol(symbol=concept_board_code, start_date=_begin_date, end_date=_end_date, df=True)
            stock_board_concept_hist_em_df = history(symbol=concept_board_code, frequency='1d', start_time=_begin_date,
                                                     end_time=_end_date,
                                                     fields='open, high, low, close, amount, volume, eob',
                                                     adjust=ADJUST_PREV, df=True)
        except Exception as e:
            time.sleep(random.uniform(1, 10))
            self.find_concept_board_index_by_name_and_begin_date_and_end_date(concept_board_name, concept_board_code,
                                                                              begin_date, end_date)
            return

        total_concept_board_index_list = stock_board_concept_hist_em_df.values.tolist()
        concept_board_index_list = list()
        for _concept_board_index in total_concept_board_index_list:
            concept_board_index = ConceptBoardIndex()
            concept_board_index.name = concept_board_name
            concept_board_index.code = concept_board_code
            concept_board_index.open_price = _concept_board_index[0]
            concept_board_index.highest_price = _concept_board_index[1]
            concept_board_index.lowest_price = _concept_board_index[2]
            concept_board_index.close_price = _concept_board_index[3]
            concept_board_index.volume = _concept_board_index[4]
            concept_board_index.turnover = _concept_board_index[5]
            concept_board_index.transaction_date = _concept_board_index[6]
            concept_board_index_list.append(concept_board_index)

        # 这行代码不能注释，否则客户端无法获取数据
        print(json.dumps(concept_board_index_list, default=lambda o: DatetimeUtil.datetime_to_str(o,
                                                                                                  DatetimeFormat.Date_Format_With_Line) if isinstance(
            o, datetime.datetime) else o.__dict__, ensure_ascii=False))

    def find_stock_by_concept_board_code(self, code):
        """
        调用akshare接口，单次返回当前时刻所有成份股
        """

        stock_board_concept_cons_em_df = None
        try:
            # stock_board_concept_cons_em_df = stock_board_concept_cons_em(symbol=name)
            stock_board_concept_cons_em_df = stock_board_concept_cons_em_2(stock_board_code=code)
            # stock_board_concept_cons_em_df = stk_get_sector_constituents(sector_code=name[3:])
        except Exception as e:
            time.sleep(random.uniform(1, 10))
            self.find_stock_by_concept_board_code(code)
            return

        stock_list = stock_board_concept_cons_em_df.values.tolist()

        code_list = list()
        for stock in stock_list:
            code_list.append(stock[1])

        print(json.dumps(code_list))

    def find_concept_board_index_by_date(self, date):
        """
        调用akshare接口，单次返回当前时刻所有概念板块指数的实时行情数据
        这个方法还没有被使用
        """

        total_concept_board_index_list = list()
        concept_board_index_dataframe = stock_board_concept_name_em()

        concept_board_index_list = concept_board_index_dataframe.values.tolist()
        total_concept_board_index_list.extend(concept_board_index_list)

        concept_board_index_list = list()
        for _concept_board_index in total_concept_board_index_list:
            concept_board_index = ConceptBoardIndex()
            concept_board_index.name = _concept_board_index[1]
            concept_board_index.code = _concept_board_index[2]
            concept_board_index.transaction_date = DatetimeUtil.str_to_datetime(date,
                                                                                DatetimeFormat.Date_Format_With_Line)
            concept_board_index.latest_price = _concept_board_index[3]
            concept_board_index.change_amount = _concept_board_index[4]
            concept_board_index.change_range = _concept_board_index[5]
            concept_board_index.total_market_value = _concept_board_index[6]
            concept_board_index.turnover_rate = _concept_board_index[7]
            concept_board_index.advance_number = _concept_board_index[8]
            concept_board_index.decline_number = _concept_board_index[9]
            concept_board_index.leading_stock_name = _concept_board_index[10]
            stock_info = self.stock_info_service.find_by_name(concept_board_index.leading_stock_name)
            if stock_info is not None:
                concept_board_index.leading_stock_code = stock_info.code_
            concept_board_index.leading_stock_change_range = _concept_board_index[11]
            concept_board_index_list.append(concept_board_index)

        # 这行代码不能注释，否则客户端无法获取数据
        print(json.dumps(concept_board_index_list, default=lambda o: DatetimeUtil.datetime_to_str(o,
                                                                                                  DatetimeFormat.Date_Format_With_Line) if isinstance(
            o, datetime.datetime) else o.__dict__, ensure_ascii=False))


if __name__ == '__main__':
    concept_board_index_api = ConceptBoardIndexApi()
    # concept_board_index_api.find_current_all_concept_board_name_and_code()
    # concept_board_index_api.find_concept_board_index_by_name_and_begin_date_and_end_date("绿色电力", "123", "19970101", "20250403")
    # concept_board_index_api.find_stock_by_concept_board_name("转基因")
    concept_board_index_api.find_concept_board_index_by_date("2025-4-3")
